package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Sound;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class SoundApiImpl implements SoundApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;


    //发送语音
    @Override
    public void send(Sound sound) {
        //设置sid唯一标识
        sound.setSid(idWorker.getNextId("sound"));
        sound.setCreated(System.currentTimeMillis());
        //设置语音状态
        sound.setState("0");
        //存入mongo数据库中
        mongoTemplate.save(sound);
    }

    //修改语音的接收状态
    @Override
    public void updateById(Sound sound) {
        Update update = Update.update("state", sound.getState());
        Query query = Query.query(Criteria.where("sid").is(sound.getSid()));
        mongoTemplate.updateFirst(query, update, Sound.class);
    }


    //随机推荐一条未被接受的语音,排除自己和好友发送的语音
    @Override
    public Sound getRecommendSound(Long userId) {
        //查询好友的id
        Query queryFriend = Query.query(Criteria.where("userId").is(userId));
        List<Friend> friendList = mongoTemplate.find(queryFriend, Friend.class);
        List<Long> ids = friendList.stream().map(Friend::getFriendId).collect(Collectors.toList());


        //查询所有未被接收的语音
        ids.add(userId);
        Query query = Query.query(Criteria.where("state").is("0")
                .and("userId").nin(ids))
                .with(Sort.by(Sort.Order.desc("created")));
        List<Sound> soundList = new ArrayList<>();
        Sound sound;
        synchronized (this) {
            soundList = mongoTemplate.find(query, Sound.class);
            if (CollUtil.isEmpty(soundList)) {
                throw new RuntimeException("接收语音失败");
            }
            //随机获取其中一个并返回
            sound = RandomUtil.randomEle(soundList);
            //接收成功,将sound的state设置为1
            sound.setState("1");
            this.updateById(sound);
        }
        return sound;
    }


}

